<?php


namespace apps\marriage\core\service;


use apps\marriage\core\logic\WeixinMpLogic;
use apps\marriage\core\logic\WxMiniLogic;
use apps\marriage\core\model\SubscribeMessageTemplate;
use apps\marriage\core\model\SystemNotice;
use apps\marriage\core\model\UserPlatform;
use apps\marriage\core\model\UserSystemNotice;
use vm\com\BaseService;

class SystemNoticeService extends BaseService
{
    /**
     * @return UserSystemNoticeService
     */
    private function getUserSystemNoticeService()
    {
        return service('UserSystemNotice', SERVICE_NAMESPACE);
    }

    /**
     * @return UserPlatformService
     */
    private function getUserPlatformService()
    {
        return service('UserPlatform', SERVICE_NAMESPACE);
    }

    /**
     * @return SiteConfigService
     */
    private function getSiteConfigService()
    {
        return service('SiteConfig', SERVICE_NAMESPACE);
    }

    /**
     * @return SubscribeMessageTemplateService
     */
    private function getSubscribeMessageTemplateService()
    {
        return service('SubscribeMessageTemplate', SERVICE_NAMESPACE);
    }

    /**
     * @return WeixinMpLogic
     */
    private function getWeixinMpLogic()
    {
        static $logic;
        if($logic !== null) {
            return $logic;
        }
        $logic = logic('WeixinMp', LOGIC_NAMESPACE);
        $logic->init([
            'app_id' => $this->getSiteConfigService()->getValueByCode('weixin_mp_app_id'),
            'app_secret' => $this->getSiteConfigService()->getValueByCode('weixin_mp_app_secret'),
            'app_token' => $this->getSiteConfigService()->getValueByCode('weixin_mp_app_token'),
            'encode_aeskey' => $this->getSiteConfigService()->getValueByCode('weixin_mp_encode_aeskey'),
        ]);
        return $logic;
    }

    /**
     * @return WxMiniLogic
     */
    private function getWxMiniLogic()
    {
        static $logic;
        if($logic !== null) {
            return $logic;
        }
        $logic = logic('WxMini', LOGIC_NAMESPACE);
        $logic->setConfig([
            'app_id' => $this->getSiteConfigService()->getValueByCode('weapp_app_id'),
            'app_secret' => $this->getSiteConfigService()->getValueByCode('weapp_app_secret'),
            'token' => $this->getSiteConfigService()->getValueByCode('weapp_app_token'),
            'EncodingAESKey' => $this->getSiteConfigService()->getValueByCode('weapp_app_encoding_aeskey'),
        ]);
        return $logic;
    }

    /**
     * @return SystemNotice
     */
    protected function getModel()
    {
        return new SystemNotice();
    }

    public function create(array $data)
    {
        $data['publish_time'] = time();
        return parent::create($data);
    }

    public function onPushSingleNotice()
    {
        $params = [
            'type' => SystemNotice::TYPE_SINGLE,
            'status' => SystemNotice::STATUS_WAIT_PULL
        ];
        $res = $this->pageListByParams($params, 30, ['page' => 1], ['id' => 'ASC']);
        if(!empty($res['data'])) {
            $weixinMpLogic = $this->getWeixinMpLogic();
            $wxMiniLogic = $this->getWxMiniLogic();
            $userSystemNoticeService = $this->getUserSystemNoticeService();
            $userPlatformService = $this->getUserPlatformService();
            $subscribeMessageTemplateService = $this->getSubscribeMessageTemplateService();
            $weappId = $this->getSiteConfigService()->getValueByCode('weapp_app_id');
            $wechatConfig = config('wechat');
            $msgTemplateId = $wechatConfig['mp_msg_templates']['job_progress_notice'];
            $weappTemplateId = $wechatConfig['msg_templates']['job_notice'];
            $logFile = DOC_PATH . 'runtime/log/daemon/'.date('Ymd').'.txt';
            foreach ($res['data'] as $item) {
                $userSystemNoticeService->create([
                    'system_notice_id' => $item['id'],
                    'recipient_id' => $item['recipient_id'],
                    'status' => UserSystemNotice::STATUS_WAIT_READ,
                    'pull_time' => time()
                ]);
                $this->updateByPk([
                    'id' => $item['id'],
                    'status' => SystemNotice::STATUS_PULLED
                ]);
                $urls = json_decode($item['url'], true);
                // 发送公众号消息
                try {
                    if($userPlatformService->checkUserSubscribedMpAccount($item['recipient_id'])) {
                        $userPlatform = $userPlatformService->info([
                            'user_id' => $item['recipient_id'],
                            'platform' => UserPlatform::PLATFORM_WX_MP
                        ]);
                        if($userPlatform) {
                            $msgData = [
                                'first' => [
                                    'value' => $item['title']
                                ],
                                'keyword1' => [
                                    'value' => 'N/A'
                                ],
                                'keyword2' => [
                                    'value' => 'N/A'
                                ],
                                'remark' => [
                                    'value' => $item['content']
                                ]
                            ];
                            $miniprogram = [
                                'appid' => $weappId,
                                'pagepath' => $urls['weapp']
//                                'pagepath' => 'pages/explore/index'
                            ];
                            $sendResult = $weixinMpLogic->sendTemplateMessage($userPlatform['open_id'], $msgTemplateId, $msgData, null, $miniprogram);
                            if($sendResult !== true) {
                                writeLog('errcode:' . $sendResult['errcode'] . '  errmsg:' . $sendResult['errmsg'], $logFile);
                            }
                        }
                    }
                } catch (\Exception $e) {
                    $log = 'FILE:' . $e->getFile() . "\r\n" . 'LINE:' . $e->getLine(). "\r\n" . 'MSG:' . $e->getMessage();
                    writeLog($log, $logFile);
                }
                // 发送小程序消息
                try {
                    $userPlatform = $userPlatformService->info([
                        'user_id' => $item['recipient_id'],
                        'platform' => UserPlatform::PLATFORM_WX_MINI
                    ]);
                    if($userPlatform) {
                        $msg = [
                            "touser" => $userPlatform['open_id'],
                            "template_id" => $weappTemplateId,
                            "page" => $urls['weapp'],
                            'data' => [
                                'thing7' => [
                                    'value' => $item['title']
                                ],
                                'thing12' => [
                                    'value' => $item['content']
                                ],
                                'thing11' => [
                                    'value' => 'N/A'
                                ]
                            ]
                        ];
                        if($wxMiniLogic->sendSubscribeMessage($msg)) {
                            $subscribeMessageTemplateService->deleteEarliestTemplateIdByOpenid($userPlatform['open_id'], $weappTemplateId, SubscribeMessageTemplate::TYPE_ONCE);
                        } else {
                            writeLog('errcode:' . $wxMiniLogic->getErrCode() . '  errmsg:' . $wxMiniLogic->getErrMsg(), $logFile);
                        }
                    }
                } catch (\Exception $e) {
                    $log = 'FILE:' . $e->getFile() . "\r\n" . 'LINE:' . $e->getLine(). "\r\n" . 'MSG:' . $e->getMessage();
                    writeLog($log, $logFile);
                }
                //TODO: 发送app消息
                try {

                } catch (\Exception $e) {
                    $log = 'FILE:' . $e->getFile() . "\r\n" . 'LINE:' . $e->getLine(). "\r\n" . 'MSG:' . $e->getMessage();
                    writeLog($log, $logFile);
                }
            }
        }
    }
}